package com.qms.repast.ui.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.qms.repast.App;
import com.qms.repast.R;
import com.qms.repast.commons.Constants;
import com.qms.repast.db.CuisineBeanDao;
import com.qms.repast.db.CuisineOrderBeanDao;
import com.qms.repast.entity.reqbean.ReqFood;
import com.qms.repast.entity.resbean.CuisineBean;
import com.qms.repast.entity.resbean.CuisineMenuBean;
import com.qms.repast.entity.resbean.CuisineOrderBean;
import com.qms.repast.ui.adapter.CardViewAdapter;
import com.qms.repast.ui.adapter.CuisineMenuAdapter;
import com.qms.repast.ui.base.BaseActivity;
import com.qms.repast.ui.presenter.CuisinePresenter;
import com.qms.repast.ui.view.ICuisineView;
import com.qms.repast.utils.AppUtils;
import com.qms.repast.utils.SpUtils;
import com.qms.repast.weidgets.cardview.CardAnimManager;
import com.qms.repast.weidgets.cardview.CustomCardView;
import com.qms.repast.weidgets.cardview.IItemHelper;
import com.qms.repast.weidgets.cardview.PullDownCallBack;
import com.qms.repast.weidgets.dragview.DragBubbleView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author 泅渡者
 * @date 2018/9/15 0015
 * @describe: 菜单界面
 */
public class CuisineActivity extends BaseActivity<CuisinePresenter> implements ICuisineView, DragBubbleView.OnBubbleStateListener {
	@BindView(R.id.iv_back)
	ImageView ivBack;
	@BindView(R.id.tv_title)
	TextView tvTitle;
	@BindView(R.id.tv_page)
	TextView tvPage;
	@BindView(R.id.alyLoopGallery)
	CustomCardView cardView;
	@BindView(R.id.rv_menu)
	RecyclerView rvMenu;
	@BindView(R.id.dragBubbleView)
	DragBubbleView dragBubbleView;
	@BindView(R.id.iv_car)
	ImageView ivCar;

	public CardViewAdapter mAdapter;
	@BindView(R.id.tv_rightImg)
	ImageView tvRightImg;

	/**
	 * 菜品类别适配器
	 */
	private CuisineMenuAdapter menuAdapter;
	/**
	 * 店铺名称
	 */
	private String shopName;
	/**
	 * 店铺ID
	 */
	private String shopId;
	/**
	 * 用户ID
	 */
	private String userId;

	private Intent mIntent;
	/**
	 * 购物车是否为空
	 */
	private boolean isEmptyCar = true;

	@Override
	protected int initLayout () {
		return R.layout.activity_cuisine;
	}

	@Override
	protected void initPresenter (Intent intent) {
		mPresenter = new CuisinePresenter(this, this);
		mIntent = intent;
		shopName = intent.getStringExtra("shopName");
		shopId = intent.getStringExtra("shopId");
	}

	@Override
	protected void initView () {

		tvTitle.setText(shopName);
		userId = SpUtils.getParam(AppUtils.getContext(), Constants.USERID, 0).toString();
		dragBubbleView.setOnBubbleStateListener(this);
		initMenu();
	}

	/**
	 * 头部分类菜单
	 */
	private void initMenu () {
		menuAdapter = new CuisineMenuAdapter(AppUtils.getContext());
		LinearLayoutManager layoutManager = new LinearLayoutManager(AppUtils.getContext());
		layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		rvMenu.setAdapter(menuAdapter);
		rvMenu.setLayoutManager(layoutManager);
		mAdapter = new CardViewAdapter(CuisineActivity.this);

		mAdapter.setmItemClickListener(new CardViewAdapter.OnItemClickListener() {
			@Override
			public void onItemClick (int position, CuisineBean item) {
				Intent intent = new Intent();
				intent.setClass(CuisineActivity.this, CuisineInfoActivity.class);
				intent.putExtra("shopId", shopId);
				intent.putExtra("userId", userId);
				intent.putExtra("itemId", item.getItemId());
				startActivity(intent);
			}
		});

		menuAdapter.setmItemClickListener(new CuisineMenuAdapter.OnItemClickListener() {
			@Override
			public void onItemClick (View view) {
				int position = rvMenu.getChildAdapterPosition(view);
				menuAdapter.setCurrentIndex(position);
				List<CuisineBean> cuisineBeans = App.getmDaoSession()
						.getCuisineBeanDao()
						.queryBuilder()
						.where(CuisineBeanDao.Properties.CategoryId.eq(menuAdapter.getCurrentItem(position).getCategoryId()))
						.list();

				mAdapter.addData(cuisineBeans);
				cardView.smoothScrollToPosition(0);
			}
		});

		setCradView();
	}

	public void setCradView () {
		cardView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
		cardView.setAdapter(mAdapter);
		// 设置滑动速度（像素/s）
		cardView.initFlingSpeed(9000)
				// 设置页边距和左右图片的可见宽度，单位dp
				.initPageParams(0, 50)
				// 设置切换动画的参数因子
				.setAnimFactor(0.1f)
				// 设置切换动画类型，目前有AnimManager.ANIM_BOTTOM_TO_TOP和目前有AnimManager.ANIM_TOP_TO_BOTTOM
				.setAnimType(CardAnimManager.ANIM_BOTTOM_TO_TOP)
				// 设置自动播放
				.autoPlay(false)
				// 设置自动播放间隔时间 ms
				.intervalTime(2000)
				// 设置初始化的位置
				.initPosition(0).setUp();
		cardView.addOnScrollListener(new RecyclerView.OnScrollListener() {
			@Override
			public void onScrollStateChanged (RecyclerView recyclerView, int newState) {
				super.onScrollStateChanged(recyclerView, newState);
			}

			@Override
			public void onScrolled (RecyclerView recyclerView, int dx, int dy) {
				super.onScrolled(recyclerView, dx, dy);
				LinearLayoutManager l = (LinearLayoutManager) recyclerView.getLayoutManager();

				String s = (l.findFirstVisibleItemPosition() + 1) + "/" + l.getItemCount();

				tvPage.setText(s);
			}
		});

	}

	@Override
	protected void initData () {
		ReqFood reqFood = new ReqFood();
		reqFood.setShopId(Integer.parseInt(shopId));
		reqFood.setUserId(Integer.parseInt(userId));
		mPresenter.getFoodList(reqFood);

		mPresenter.selectItemCount(userId, shopId);
	}

	@Override
	protected void onResume () {
		super.onResume();
		userId = SpUtils.getParam(AppUtils.getContext(), Constants.USERID, 0).toString();
		mPresenter.selectItemCount(userId, shopId);
	}

	@Override
	public void onDrag () {
	}

	@Override
	public void onMove () {
	}

	@Override
	public void onRestore () {
	}

	@Override
	public void onDismiss () {
		//气泡消失时清除购物车
		App.getmDaoSession()
				.getCuisineOrderBeanDao()
				.queryBuilder()
				.where(
						CuisineOrderBeanDao.Properties.UserId.eq(userId),
						CuisineOrderBeanDao.Properties.ShopId.eq(shopId)
				)
				.buildDelete().executeDeleteWithoutDetachingEntities();
		//购物车置空
		isEmptyCar = true;
	}

	@Override
	public void showUi () {
		//填充菜单分类
		List<CuisineMenuBean> cuisineMenuBeans = App.getmDaoSession().getCuisineMenuBeanDao().loadAll();
		menuAdapter.addData(cuisineMenuBeans);
		if (null != cuisineMenuBeans && cuisineMenuBeans.size() > 0) {
			List<CuisineBean> cuisineBeans = App.getmDaoSession()
					.getCuisineBeanDao()
					.queryBuilder()
					.where(CuisineBeanDao.Properties.CategoryId.eq(cuisineMenuBeans.get(0).getCategoryId()))
					.list();

			if (null != mAdapter) {
				mAdapter.addData(cuisineBeans);
			} else {
				mAdapter = new CardViewAdapter(CuisineActivity.this);
				mAdapter.addData(cuisineBeans);
			}

		}

		setCradView();
		//先实例化Callback
		ItemTouchHelper.Callback callback = new PullDownCallBack(cardView, mAdapter, new IItemHelper() {
			@Override
			public void onItemMove (int fromPosition, int toPosition) {

			}

			@Override
			public void onItemSwipe (int position) {
				/**
				 * 此处是卡片下滑操作
				 * 限定多次滑动无效
				 */
				CuisineBean cuisineBean = mAdapter.getCurrentItem(position);

				if (null != cuisineBean) {

					//在购物车中查找该菜品
					List<CuisineOrderBean> cuisineOrderBeans = App.getmDaoSession()
							.getCuisineOrderBeanDao()
							.queryBuilder()
							.where(
									CuisineOrderBeanDao.Properties.UserId.eq(userId),
									CuisineOrderBeanDao.Properties.ShopId.eq(shopId),
									CuisineOrderBeanDao.Properties.ItemId.eq(cuisineBean.getItemId())
							).list();
					//菜品已经存在 则下滑不起作用（后续如果要下滑可多次加菜，更改此处即可）
					if (null != cuisineOrderBeans && cuisineOrderBeans.size() > 0) {

					}
					//菜品不存在 向购物车表增加该信息
					else {
						CuisineOrderBean cuisineOrderBean = new CuisineOrderBean();
						cuisineOrderBean.setUserId(userId);
						cuisineOrderBean.setShopId(shopId);
						cuisineOrderBean.setItemId(cuisineBean.getItemId());
						cuisineOrderBean.setItemNum(1);
						App.getmDaoSession().getCuisineOrderBeanDao().insert(cuisineOrderBean);
					}
				}

				mPresenter.selectItemCount(userId, shopId);

				if (!dragBubbleView.isActivated()) {
					dragBubbleView.reCreate();
				}
			}
		});
		//用Callback构造ItemtouchHelper
		ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
		//调用ItemTouchHelper的attachToRecyclerView方法建立联系
		touchHelper.attachToRecyclerView(cardView);


	}

	@Override
	public void showItemCount (int sum) {
		dragBubbleView.setText(sum + "");
		if (sum > 0) {
			isEmptyCar = false;
		} else {
			isEmptyCar = true;
		}
	}

	@Override
	protected void onDestroy () {
		super.onDestroy();
		if (cardView != null) {
			// 释放资源
			cardView.release();
		}
	}

	@OnClick({R.id.iv_back, R.id.tv_rightImg, R.id.iv_car})
	public void onViewClicked (View view) {
		switch (view.getId()) {
			case R.id.iv_back:
				finish();
				break;
			case R.id.tv_rightImg:
				break;
			case R.id.iv_car:
				//购物车为空，提示加菜
				if (isEmptyCar) {

				}
				//购物车非空，跳转
				else {
					mIntent = new Intent(CuisineActivity.this, OrderReviewActivity.class);
					mIntent.putExtra("shopName", shopName);
					mIntent.putExtra("shopId", shopId);
					mIntent.putExtra("userId", userId);
					startActivity(mIntent);
				}
				break;
			default:
				break;
		}
	}


}
